//
//  SWPreviewViewController.swift
//  YiyaPuzzleDemo
//  预览页（左右两页）
//  Created by linhan on 16/9/28.
//  Copyright © 2016年 test. All rights reserved.
//

import Foundation
import UIKit
class SWPreviewViewController: SWBaseViewController,UIPageViewControllerDelegate,UIPageViewControllerDataSource
{
    private var _pages:[SWPage] = []
    
    var currIndex:Int = 0
    //左边两个 跟 右边 两个用于轮换，中间两个，共6个
    private let VCCacheCount:Int = 6
    private let PageCountPerUnit:Int = 2
    
    private let PageViewInsets:UIEdgeInsets = UIEdgeInsetsMake(20, 60, 20, 20)
    
    private var _pageController:UIPageViewController?
    private var _viewControllers:[UIViewController] = []
    
    init(pages:[SWPage])
    {
        super.init(nibName: nil, bundle: nil)
        _pages = pages
        //如果是单数页，补一个空白页
        if _pages.count % 2 != 0
        {
            let page:SWPage = SWPage()
            page.whitespace = true
            _pages.append(page)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit
    {
        print("DEINIT SWPreviewViewController")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask
    {
        return UIInterfaceOrientationMask.landscapeLeft
    }
    
    override var shouldAutorotate: Bool
    {
        return false
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation
    {
        return .landscapeLeft
    }
    
    override func viewWillLayoutFirstTime() {
        setup()
    }
    
    private func setup()
    {
        automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = UIColor(white: 0.95, alpha: 1)
        
        if _pages.count < 2
        {
            return
        }
        
        var beginindex:Int = currIndex - PageCountPerUnit
        if (currIndex == 0)
        {
            beginindex = 0
        }
        else if (currIndex >= _pages.count - PageCountPerUnit)
        {
            beginindex = _pages.count - VCCacheCount
        }
        
        for i in beginindex..<beginindex + VCCacheCount
        {
            if (i < 0) {
                continue;
            }
            if (i > _pages.count - 1) {
                break
            }
            let detailViewController:SWPageViewController = SWPageViewController()
            detailViewController.previewMode = true
            detailViewController.page = _pages.valueAt(i)
            _viewControllers.append(detailViewController)
        }
        
        let option:[String : AnyObject] = [UIPageViewControllerOptionSpineLocationKey:UIPageViewControllerSpineLocation.mid.rawValue as AnyObject]
        _pageController = UIPageViewController(transitionStyle: .pageCurl, navigationOrientation: .horizontal, options: option)
        _pageController?.dataSource = self
        _pageController?.delegate = self
        
        
        var VCIndex:Int = PageCountPerUnit
        if currIndex <= 1
        {
            VCIndex = 0
        }
        else if currIndex >= _pages.count - PageCountPerUnit
        {
            VCIndex = _viewControllers.count - PageCountPerUnit
        }
        
        var viewControllers:[UIViewController]? = []
        if let firstPage = _viewControllers.valueAt(VCIndex)
        {
            viewControllers?.append(firstPage)
        }
        if let secondPage = _viewControllers.valueAt(VCIndex + 1)
        {
            viewControllers?.append(secondPage)
        }
        _pageController?.setViewControllers(viewControllers, direction: .forward, animated: true, completion: nil)
        
        //翻页组件位置
        let ContainerSize = CGSizeMake(view.width - PageViewInsets.left - PageViewInsets.right, view.height - PageViewInsets.top - PageViewInsets.bottom)
        let BookFullPageSize = SW.Config.BookFullPageSize
        let scale:CGFloat = ViewUtil.getAdaptiveScale(BookFullPageSize.width, targetH: BookFullPageSize.height, containerW: ContainerSize.width, containerH: ContainerSize.height)
        let PageViewSize = CGSizeMake(BookFullPageSize.width * scale, BookFullPageSize.height * scale)
        let PageViewRect = CGRectMake(PageViewInsets.left + (ContainerSize.width - PageViewSize.width) * 0.5, PageViewInsets.top + (ContainerSize.height - PageViewSize.height) * 0.5, PageViewSize.width, PageViewSize.height)
        _pageController?.view.frame = PageViewRect
        addChildViewController(_pageController!)
        view.addSubview(_pageController!.view)
        
        
        let closeBtn:UIButton = UIButton(type: .system)
        closeBtn.setTitle("X", for: .normal)
        closeBtn.sizeToTouchEasy()
        closeBtn.addTarget(self, action: #selector(closeBtnTapped), for: .touchUpInside)
        view.addSubview(closeBtn)
        
        let commitBtn:UIButton = UIButton(type: .system)
        commitBtn.setTitle("提交", for: .normal)
        commitBtn.sizeToTouchEasy()
        commitBtn.addTarget(self, action: #selector(commitBtnTapped), for: .touchUpInside)
        commitBtn.frame = CGRectMake(0, closeBtn.bottom, commitBtn.width, commitBtn.height)
        //view.addSubview(commitBtn)
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?
    {
        guard let index = _viewControllers.index(of: viewController) else
        {
            return nil
        }
        return _viewControllers.valueAt(index - 1)
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?
    {
        guard let index = _viewControllers.index(of: viewController) else
        {
            return nil
        }
        return _viewControllers.valueAt(index + 1)
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool)
    {
        //取左边这个作为当前页面索引
        if let currentViewController = pageViewController.viewControllers?.first, completed
        {
            let index = _viewControllers.index(of: currentViewController) ?? -1
            
            // 处理四种特殊情况
            //处于中间页尽管递增
            if (currIndex == 0) {
                if (index == 2) {
                    currIndex += PageCountPerUnit
                }
                return;
            }
            
            if (currIndex == 2 && index == 0) {
                currIndex -= 2;
                return;
            }
            
            if (currIndex == _pages.count - 2) {
                if (index == 2) {
                    currIndex -= 2;
                }
                return;
            }
            
            if (currIndex == _pages.count - 4 && index == 4) {
                currIndex += 2;
                return;
            }
            
            if (index == VCCacheCount - 2)
            {
                //右侧不足时，从左侧拿两个放右侧
                currIndex += PageCountPerUnit
                if (currIndex >= _pages.count - 2) {
                    return;
                }
                
                //右2
                if let detailViewController = _viewControllers.removeAtIndexSafely(0),
                    let data = _pages.valueAt(currIndex + 2)
                {
                    (detailViewController as? SWPageViewController)?.page = data
                    _viewControllers.insert(detailViewController, at: _viewControllers.count)
                }
                
                //右1
                if let detailViewController = _viewControllers.removeAtIndexSafely(0),
                    let page = _pages.valueAt(currIndex + 3)
                {
                    (detailViewController as? SWPageViewController)?.page = page
                    _viewControllers.insert(detailViewController, at: _viewControllers.count)
                }
            }
            else if (index == 0)
            {
                //左侧不足时，从右侧拿两个放左边
                currIndex -= PageCountPerUnit;
                if (currIndex <= 0) {
                    return;
                }
                
                //左2
                if let detailViewController = _viewControllers.removeAtIndexSafely(5),
                    let page = _pages.valueAt(currIndex - 1)
                {
                    (detailViewController as? SWPageViewController)?.page = page
                    _viewControllers.insert(detailViewController, at: 0)
                }
                
                //左1
                if let detailViewController = _viewControllers.removeAtIndexSafely(5),
                    let page = _pages.valueAt(currIndex - 2)
                {
                    (detailViewController as? SWPageViewController)?.page = page
                    _viewControllers.insert(detailViewController, at: 0)
                }
            }
        }//end completed
    }
    
    //跳转到某页
    private func jumbIndex(index target:Int)
    {
        print("jumbIndex:", index)
        var newIndex:Int = max(min(target, _pages.count - 1), 0)
        newIndex = newIndex % 2 == 0 ? newIndex : newIndex - 1
        if newIndex != currIndex
        {
            let vcCount = _viewControllers.count
            let direction:UIPageViewControllerNavigationDirection = newIndex > currIndex ? .forward : .reverse
            currIndex = newIndex
            let beginIndex:Int = min(max(0, currIndex - PageCountPerUnit), _pages.count - vcCount)
            
            for (i, viewController) in _viewControllers.enumerated()
            {
                let bIndex = beginIndex + i
                if let page = _pages.valueAt(bIndex)
                {
                    (viewController as? SWPageViewController)?.page = page
                }
            }
            
            var aIndex:Int = PageCountPerUnit
            if currIndex == 0
            {
                aIndex = 0
            }
            else if currIndex == _pages.count - PageCountPerUnit
            {
                aIndex = _viewControllers.count - PageCountPerUnit
            }
            
            var viewControllers:[UIViewController]? = []
            if let firstPage = _viewControllers.valueAt(aIndex)
            {
                viewControllers?.append(firstPage)
            }
            if let secondPage = _viewControllers.valueAt(aIndex + 1)
            {
                viewControllers?.append(secondPage)
            }
            _pageController?.setViewControllers(viewControllers, direction: direction, animated: false, completion: nil)
        }
        
    }
    
    @objc private func closeBtnTapped()
    {
        dismiss(animated: true, completion: nil)
        //navigationController?.popViewControllerAnimated(true)
    }
    
    //提交前进行空白页、空白格检查
    @objc private func commitBtnTapped()
    {
        if let book = SWBookManager.sharedManager().book
        {
            SWPageManager.sharedManager().photoCompletenessCheck(book, successCallback: {
                //所有的图都填满了
                /**
                SWPageManager.sharedManager().generationAllPage(book, successCallback: {
                    print("全部生成完成")
                    
                    
                    
                })**/
                
                SWUploadManager.sharedManager().uploadAllPage(book, successCallback: {
                    print("全部上传完成")
                })
                
            }, failCallback: {[weak self]page in
                
                if let index = self?._pages.index(of: page)
                {
                    DispatchQueue.main.async(execute: {
                        Alert.show("第\(index + 1)页缺图")
                        self?.jumbIndex(index: index)
                    })
                    
                }
            
            })
        }
        
        
        //生成所有页面
        
        //上传所有页面
    }
    
    
    
    
}
